package com.ITD.service.Impl;

import com.ITD.pojo.Data;
import com.ITD.pojo.LoginParam;
import com.ITD.pojo.User;
import com.ITD.service.LoginService;
import com.ITD.service.UserService;
import com.ITD.utils.JWTUtils;
import com.ITD.vo.ErrorCode;
import com.ITD.vo.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public Result login(LoginParam loginParam) {
        /**登陆方法
         * 核心
         *      1.json对象获取账号密码
         *      2.校验数据库用户是否存在
         *      3.成功则返回token给前端，失败则报错
         * 实现
         * 1.判空
         * 2.loginParam获取账号密码
         * 3.加密密码（数据库中存的非明文密码）
         * 4.查找表中用户是否存在，不存在，登录失败
         * 5.存在，生成token返回前端
         * 6.token存在redis中，设置属性，删除原先
         */
        //获取数据
        String username = loginParam.getUsername();
        String password = loginParam.getPassword();
        String sha1pwd = DigestUtils.sha1Hex(password);

        //查询表数据
        User user = userService.findUser(username, sha1pwd);
        System.out.println(user);
        if (user == null)
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg(),"账户不存在");

        //成功，生成token
        String Authorization = JWTUtils.createToken(user.getId(),user.getUserName(),"user");
        System.out.println(Authorization);

        //token存入redis
        redisTemplate.opsForValue().set("TOKEN_"+Authorization, username,60*60*48, TimeUnit.MINUTES);


        //返回登录数据
        Data regist =new Data();
        regist.setToken(Authorization);
        return Result.success(regist);

    }
}
